/*
 * WCIAppServConnector.cpp
 *
 *  Created on: Apr 13, 2017
 *      Author: zhangjf
 */

#include <Poco/Types.h>
#include <Poco/Exception.h>

using namespace Poco;

#include "Helper.h"
#include "Packet.h"
#include "PacketReceiver.h"
#include "MainApplication.h"
#include "WCIAppServConnector.h"

StreamSocket WCIAppServConnector::_streamSocket;


void WCIAppServConnector::connect()
{
	SocketAddress sa("127.0.0.1", 12345);
	_streamSocket.close();
	_streamSocket.connect(sa);
	poco_information(Application::instance().logger(), "Connect to appserv");
}


bool WCIAppServConnector::request(std::string& strRequest, std::string& strResponse)
{
	poco_information(Application::instance().logger(), "enter " + std::string(__func__));
	//reconnect();

	bool blRet = false;
	bool blSent = false;

	PacketHeader header;
	header.type = MSG_TYPE::MSG_TYPE_JSONRPC;
	header.length = strRequest.length() + 1 + sizeof(PacketHeader);

	poco_information(Application::instance().logger(), "send request to appserv...");
	while (!blSent)
	{
		try
		{
			//poco_information(Application::instance().logger(), "aaaaaaa:length" + std::to_string(header.length) + ", sizeof(PacketHeader): " + std::to_string(sizeof(PacketHeader)));
			_streamSocket.sendBytes(&header, sizeof(header));
			//poco_information(Application::instance().logger(), "aaaaaaa: " + strRequest);
			_streamSocket.sendBytes(strRequest.c_str(), strRequest.length() + 1);
			blSent = true;
		}
		catch(Exception& exc)
		{
			poco_information(Application::instance().logger(), exc.displayText() + ": disconnect to the appserv");
		}

		try
		{
			if (!blSent)
			{
				connect();
			}
		}
		catch(Exception& exc)
		{
			poco_information(Application::instance().logger(), exc.displayText() + ": connect to the appserv failed");
		}
	}

	poco_information(Application::instance().logger(), "send to appserv successful.");

	PacketReceiver receiver(_streamSocket);
	Packet::Ptr packet;

	while (true)
	{
		packet = receiver.recv();
		if (!packet.isNull())
		{
			blRet = true;
			break;
		}
	}
	strResponse.assign(packet->getData());
	poco_information(Application::instance().logger(), "response from appserv: " + strResponse);

	return blRet;
}
